<?php

class MyFunctionCustom extends CActiveRecord {
    /*
     * DTOAN
     *
     */

    public static $status = array(
        STATUS_INACTIVE => 'Hủy',
        STATUS_ACTIVE => 'Kích hoạt',
    );

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @var type
     */
    public static $status_booking = array(
        STATUS_PENDING => 'Pending',
        STATUS_DELIVER => 'Deliver',
        STATUS_FINISH => 'Finish',
    );
    public static $role = array(
        3 => 'Content user',
        4 => 'Ticket user'
    );

    public static function getRole($roleID) {
        $arrRole = MyFunctionCustom::$role;
        if (!empty($roleID) && array_key_exists($roleID, $arrRole))
            return $arrRole[$roleID];
    }

    public static $arrAcess = array(
        //admin,manager full access
        //Content user
        3 => array(
            'default',
            'event',
            'cms',
            'gallery'
        ),
        //Ticket user
        4 => array(
            'default',
            'ticket',
            'booked'
        ),
    );

    public static function checkAccess($role_id) {
        $getcontroller = Yii::app()->controller->id;
        $access = MyFunctionCustom::$arrAcess;

        if (!in_array($getcontroller, $access[$role_id])) {
            Yii::app()->user->setFlash('messageError', 'You are not authorized to perform this action');
            Yii::app()->request->redirect(Yii::app()->createAbsoluteUrl('bookingsystem/site/dine'));
        }
    }

    public static function getStatus($value) {
        if (!is_null($value)) {
            $arrStatus = MyFunctionCustom::$status;
            if (array_key_exists($value, $arrStatus)) {
                return $arrStatus[$value];
            }
        }
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @param type $value
     * @return type
     */
    public static function getStatusBooking($value) {
        if (!is_null($value)) {
            $arrStatus = MyFunctionCustom::$status_booking;
            if (array_key_exists($value, $arrStatus)) {
                return $arrStatus[$value];
            } else {
                return "";
            }
        }
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @param type $string
     * @param type $your_desired_width
     * @return type
     */
    public static function ShortenString($string, $your_desired_width) {
        $string = strip_tags($string);
        if (strlen($string) < $your_desired_width)
            return $string;
        $res = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $your_desired_width));
        return $res . '...';
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @param type $str
     * @return type
     */
    public static function remove_vietnamese_accents($str) {
        $accents_arr = array(
            "à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă",
            "ằ", "ắ", "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "�?",
            "ế", "ệ", "ể", "ễ",
            "ì", "í", "ị", "ỉ", "ĩ",
            "ò", "ó", "�?", "�?", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ",
            "�?", "ớ", "ợ", "ở", "ỡ",
            "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ",
            "ỳ", "ý", "ỵ", "ỷ", "ỹ",
            "đ",
            "À", "�?", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă",
            "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ",
            "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ",
            "Ì", "�?", "Ị", "Ỉ", "Ĩ",
            "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "�?", "Ộ", "Ổ", "Ỗ", "Ơ",
            "Ờ", "Ớ", "Ợ", "Ở", "Ỡ",
            "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ",
            "Ỳ", "�?", "Ỵ", "Ỷ", "Ỹ",
            "�?"
        );

        $no_accents_arr = array(
            "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
            "a", "a", "a", "a", "a", "a",
            "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
            "i", "i", "i", "i", "i",
            "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o",
            "o", "o", "o", "o", "o",
            "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u",
            "y", "y", "y", "y", "y",
            "d",
            "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
            "A", "A", "A", "A", "A",
            "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E",
            "I", "I", "I", "I", "I",
            "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O",
            "O", "O", "O", "O", "O",
            "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U",
            "Y", "Y", "Y", "Y", "Y",
            "D"
        );

        return str_replace($accents_arr, $no_accents_arr, $str);
    }

    public static function formatDate($value) {
        if (!is_null($value))
            return date('d-m-Y', strtotime($value));
        return '';
    }

    public static function getDropdownlistLanguage() {
        $result = Language::model()->findAll();
        if (count($result) > 0) {
            return CHtml::listData($result, 'id', 'name');
        }
        return array();
    }

    public static function getDropdownlistCategoryEvent() {
        $result = EventCategory::model()->findAll();
        if (count($result) > 0) {
            return CHtml::listData($result, 'id', 'name');
        }
        return array();
    }

    public static function getDropdownlistGalleries() {
        $result = Gallery::model()->findAll();
        if (count($result) > 0) {
            return CHtml::listData($result, 'id', 'name');
        }
        return array();
    }

    public static function addMoreTag($model, $tagMore) {
        $arr = array();
        if ($tagMore) {
            $tag = explode(',', trim($tagMore));
            if (!empty($tag) && is_array($tag)) {
                foreach ($tag as $k => $v) {
                    //check tag
                    $slug = str_replace(' ', '-', strtolower(StringHelper::remove_vietnamese_accents(trim($v))));
                    $checkTag = Tags::model()->findByAttributes(array('slug' => $slug));
                    if ($checkTag)
                        $arr[] = $checkTag->id;
                    else {
                        //save
                        $addmore = new Tags();
                        $addmore->name = $v;
                        if ($addmore->save())
                            $arr[] = $addmore->getPrimaryKey();
                    }
                }
            }
        }
        return $arr;
    }

    // Custom by Hong Ta: 12-12-2013
    public static function getEvent() {
        $event = Event::model()->findAll();
        if (count($event) > 0) {
            return CHtml::listData($event, 'id', 'event_code');
        }
        return array();
    }

    /**
     * <Jason>
     * <EMail: pmhai90@gmail.com>
     * @return type
     */
    public static function getEventTicket() {
        $event = Event::model()->findAll();
        $list = array();
        if (count($event) > 0) {
            foreach ($event as $value) {
                $list[$value->id] = $value->event_code . "_" . $value->translate->main_title;
            }
        }
        return $list;
    }

    /**
     * <Jason>
     * <EMail: pmhai90@gmail.com>
     * @return type
     */
    public static function formatDateTime($string, $format = 'd-M-y') {
        return empty($string) ? '' : date($format, strtotime($string));
    }

    public static function getTag($arrTagId) {
        if (!empty($arrTagId)) {
            $tag = json_decode($arrTagId);
            if (!empty($tag) && is_array($tag)) {
                $criteria = new CDbCriteria;
                $criteria->addInCondition('t.id', $tag);
                $result = Tags::model()->findAll($criteria);
                if ($result) {
                    $arr = CHtml::listData($result, 'id', 'name');
                    return implode(',', $arr);
                }
            }
        }
    }

    public static function maxFileUpload() {
        return (5 * 1024 * 1024);
    }

    public static function saveMap($model, $objectFile) {
        $ImageProcessing = new ImageProcessing();
        $ImageProcessing->createDirectoryByPath('data/map');
        $ImageProcessing->folder = '/data/map';
        $objectFile->saveAs(Yii::app()->basePath . "/../data/map/$model->fileImage");
        return $model->fileImage;
    }

    public static function savePic($model, $objectFile) {
        $ImageProcessing = new ImageProcessing();
        $ImageProcessing->createDirectoryByPath('data/pic');
        $ImageProcessing->folder = '/data/pic';
        $objectFile->saveAs(Yii::app()->basePath . "/../data/pic/$model->fileImage");
        return $model->fileImage;
    }

    public static function saveCover($model, $cover_image) {
        $ImageProcessing = new ImageProcessing();
        $ImageProcessing->createDirectoryByPath('data/cover');
        $ImageProcessing->folder = '/data/cover';
        $cover_image->saveAs(Yii::app()->basePath . "/../data/cover/$model->cover_image");
        return $model->cover_image;
    }

    public static function DeleteFile($model, $fieldName, $folderName) {
        $ImageProcessing = new ImageProcessing();
        $ImageProcessing->folder = "/data/$folderName";
        if ($model->$fieldName != null) {
            $ImageProcessing->deleteFile($ImageProcessing->folder . '/' . $model->$fieldName);
        }
        // $cover_image->saveAs(Yii::app()->basePath . "/../data/cover/$model->cover_image");
        // return $model->cover_image;
    }

    // Convert Object to Array So That Encode JSON

    public static function getFacebookLoginUrl($redirect_uri = '') {
        $params = array(
            'scope' => 'publish_stream,email,user_likes,user_about_me,user_location,user_birthday',
            'redirect_uri' => Yii::app()->createAbsoluteUrl('site/fblogin')
        );

        if (!empty($redirect_uri)) {
            $session = Yii::app()->session;
            $session['FACEBOOK_REDIRECT_URI'] = $redirect_uri;
        }
        return Yii::app()->facebook->getLoginUrl($params);
    }

    public static function saveUserFacebook() {

        $access = Yii::app()->facebook->getAccessToken();
        $user_info = Yii::app()->facebook->api('/me?access_token=' . $access);

        //arrID Friends
        $friends = Yii::app()->facebook->api('/me/friends');
        $arrFriend = array();
        $arrAvatarFB = array();
        if (isset($friends['data']) && count($friends['data']) > 0) {
            foreach ($friends['data'] as $key => $value) {
                $arrFriend[$value['id']] = $value['id'];
                $arrAvatarFB[$value['id']]['name'] = $value['name'];
                $arrAvatarFB[$value['id']]['avata'] = '<img src="https://graph.facebook.com/' . $value['id'] . '/picture" title="' . $value['name'] . '"/>';
            }
        }
        Yii::app()->session['facebook_firend'] = $arrFriend;
        Yii::app()->session['facebook_firend_avata'] = $arrAvatarFB;





        $oauth_uid = $user_info['id'];
        $model = Users::model()->find('oauth_uid="' . $oauth_uid . '"');
        if (is_null($model)) {
            $model = Users::model()->find('email="' . $user_info['email'] . '"');
            if (!is_null($model)):
                $model->oauth_provider = 'facebook';
                $model->oauth_uid = $user_info['id'];
                $model->access_token = $access;
                $model->facbook_id = $user_info['id'];
                $model->update();
            else:
                $model = new Users();
                $model->oauth_provider = 'facebook';
                $model->oauth_uid = $user_info['id'];
                $model->facbook_id = $user_info['id'];
                $model->access_token = $access;
                $model->email = $user_info['email'];
                $model->username = $user_info['email'];
                $model->first_name = $user_info['first_name'];
                $model->last_name = $user_info['last_name'];
                $model->role_id = 0;
                $model->application_id = 2;
                $model->facbook_id = $user_info['id'];
                $model->status = 1;
                $model->temp_password = MyFunctionCustom::randString(6);
                $model->save();
                $model->password_hash = md5($model->temp_password);
                $model->update();
            endif;
        }else {
            $model->access_token = $access;
            $model->update(array('access_token'));
        }

        if (isset(Yii::app()->user->id))
            return true;

        return MyFunctionCustom::autologin($model);
    }

    public static function autologin($modelUser) {
        $modelLogin = new LoginFormFE();
        $modelLogin->username = $modelUser->username;
        $modelLogin->password = $modelUser->temp_password;
        if ($modelLogin->validate()) {
            return true;
        }
        return false;
    }

    public static function getLinkYoutube($link) {
        return str_replace(array('http://www.youtube.com/watch?v=', 'http://youtu.be/'), array('', ''), trim($link));
    }

    public static function randString($length = 6, $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
        $str = '';
        $count = strlen($charset);
        while ($length--) {
            $str .= $charset[mt_rand(0, $count - 1)];
        }
        return $str;
    }

    public static function getLanguage() {
        $lang = Language::model()->findAll();
        if ($lang)
            return CHtml::listData($lang, 'id', 'name');
        return array();
    }

    public static function getPagetype() {
        $criteria = new CDbCriteria();
        $criteria->select = 't.*';
        //$criteria->with= 'menu';
        $criteria->condition = 't.active = :active AND t.static = :static';
        $criteria->params = array(':active' => 1, ':static' => 1);
        $data = Menu::model()->findAll($criteria);
        $arrStatic = array();
        foreach ($data as $k => $m) {
            $arrStatic[$m['id']] = $m['name'];
        }
//        return array(
//            'gioi-thieu' => 'Giới thiệu',
//            //'help' => 'Help',
//        );
        return $arrStatic;
    }

    public static function getPayment($paymenttype) {
        switch ($paymenttype) {
            case 1:
                return 'COD';
                break;
            case 2:
                return 'Creadit Card';
                break;
            default:
                return 'ATM';
                # code...
                break;
        }
    }

    /**
     * <Jason>
     * <Email: pmhai90@gmail.com>
     * @return type
     */
    public static function getPaymentType() {
        return array(
            0 => 'Normarl',
            1 => 'Gold',
            2 => 'Luxury'
        );
    }

    public static function saveTickBooked($model) {
        $flag = FALSE;

        if (isset($_POST['ticket']['check']) && is_array($_POST['ticket']['check'])) {
            $userlogin = Yii::app()->session['LOGGED_USER'];
            // When update server should be remove it
            if ($userlogin == null) {
                $user = Users::model()->findByPk(169);
            } else {
                $user = Users::model()->findByPk($userlogin->id);
            }

            if ($user) {
                // var_dump($_POST['ticket']['quantity']);
                // var_dump($_POST['ticket']['check']);
                // die();
                foreach ($_POST['ticket']['check'] as $key => $v) {
                    if (isset($_POST['ticket']['quantity'][$key]) && $_POST['ticket']['quantity'][$key] > 0) {
                        $booked = new Booked();
                        date_default_timezone_set('UTC');
                        $booked->booked_date = date('Y-m-d');
                        $booked->booked_time = date('h:i');
                        // When update server should be remove it
                        if ($model->user_id == null) {
                            $booked->user_id = $user->id;
                        } else {
                            $booked->user_id = $model->user_id;
                        }

                        $booked->ticket_id = $key;
                        $booked->event_id = $model->event_id;
                        $booked->facbook_id = $user->oauth_uid;
                        $booked->additional_note = $model->additional_note;
                        $booked->payment_type = $model->payment_type;
                        $booked->payment_address = $model->payment_address;
                        $booked->status = $model->status;
                        $booked->deliver_address = $model->deliver_address;
                        $booked->phone = $model->phone;
//                        if(isset(Yii::app()->session['ghe'][$model->ticket_id])){
                        if (isset($_SESSION['ghe'][$model->ticket_id])) {

                            $booked->so_ghe = json_encode($_SESSION['ghe'][$model->ticket_id]);
                            unset($_SESSION['ghe'][$model->ticket_id]);
                        }

                        $booked->quantity = $_POST['ticket']['quantity'][$key];
                        $booked->save();
                        $flag = true;
                    }
                }
            }
        }
        return array('flag' => $flag, 'ticket_id' => $booked->ticket_id);
    }

    /**
     * Pham Duy Toan
     * Facebook friend
     * ghostkissboy12@gmail.com
     *
     */
    public static function CheckFriendBookedFb($ticked_id) {
        $arrFreind = isset(Yii::app()->session['facebook_firend']) ? Yii::app()->session['facebook_firend'] : array();
        if (is_array($arrFreind) && count($arrFreind) > 0) {
            $book = Booked::model()->findAllByAttributes(array('ticket_id' => $ticked_id));
            if ($book) {
                $arrBook = CHtml::listData($book, 'facbook_id', 'facbook_id');
                if (count($arrBook) > 0) {
                    $arrMere = array_intersect_assoc($arrBook, $arrFreind);
                    return count($arrMere);
                }
            }
            return 0;
        }
        return 0;
    }

    /**
     * Pham Duy Toan
     * Facebook Avata
     * ghostkissboy12@gmail.com
     *
     */
    public static function CheckFriendBookedFbAvata($ticked_id) {
        $arrFreind = isset(Yii::app()->session['facebook_firend']) ? Yii::app()->session['facebook_firend'] : array();
        $html = '';
        if (is_array($arrFreind) && count($arrFreind) > 0) {
            $book = Booked::model()->findAllByAttributes(array('ticket_id' => $ticked_id, 'status' => STATUS_FINISH));
            if ($book) {
                $arrBook = CHtml::listData($book, 'facbook_id', 'facbook_id');
                if (count($arrBook) > 0) {
                    $arrMere = array_intersect_assoc($arrBook, $arrFreind);
                    if (count($arrMere) > 0) {
                        $arrAvata = isset(Yii::app()->session['facebook_firend_avata']) ? Yii::app()->session['facebook_firend_avata'] : array();
                        if (count($arrAvata) > 0) {

                            $html.='<ul class="avata_facebook" style="list-style:none;">';
                            foreach ($arrMere as $k => $v) {
                                $html.='<li style="margin-left:10px;margin-bottom:5px;"><a href="https://www.facebook.com/' . $v . '" target="_blank" ><img style="border:1px solid #a5a5a5;padding:3px;float:left" src="https://graph.facebook.com/' . $v . '/picture" title="' . $arrAvata[$v]['name'] . '"/><p style="font-weight:bold;font-size:12px;padding:20px;line-height:16px">' . $arrAvata[$v]['name'] . '</p></a></li>';
                            }
                            $html.='</ul>';
                        }
                    }
                }
                return $html;
            }
            return $html;
        }
        return $html;
    }

    /**
     * Pham Duy Toan
     * get pepele book event
     * ghostkissboy12@gmail.com
     *
     */
    public static function GetBookevent($ticked_id) {
        $criteria = new CDbCriteria;
        $criteria->compare('t.event_id', $ticked_id);
        $criteria->compare('t.status', STATUS_FINISH);
        $criteria->group = 't.user_id';
        $book = Booked::model()->findAll($criteria);
        if ($book)
            return count($book);
        return 0;
    }

    //Premodify -- 17-02 Current not modify yet
    public static function getInfoEvent($event_id, $language) {
        $event = Translate::model()->findByAttributes(array('event_id' => $event_id, 'language_id' => $language));
        if ($event)
            return $event->main_title;
        return null;
    }

    /**
     * Pham Duy Toan
     * Check delete gallery
     * ghostkissboy12@gmail.com
     *
     */
    public static function checkDeleteGallery($galleryID) {
        $criteria = new CDbCriteria;
        $criteria->compare('t.gallery_id', $galleryID);
        $gallery = Event::model()->find($criteria);
        if ($gallery)
            return true;
        return false;
    }

    public static function getFacebookLoginUrlTest($redirect_uri = '') {
        $params = array(
            'display' => 'popup',
            'scope' => 'publish_stream,email,user_likes,user_about_me,user_location,user_birthday',
            'redirect_uri' => Yii::app()->createAbsoluteUrl('site/requirelogin')
        );

        if (!empty($redirect_uri)) {
            $session = Yii::app()->session;
            $session['FACEBOOK_REDIRECT_URI'] = $redirect_uri;
        }
        return Yii::app()->facebook->getLoginUrl($params);
    }

    public static function getCategoryParent() {
        $criteria = new CDbCriteria;
        $criteria->condition = 't.active=:active';
        $criteria->params = array(':active' => 1);
        $criteria->order = 't.order asc';
        $data = Category::model()->findAll($criteria);
        $arrMenu = array();
        foreach ($data as $d) {
            $arrMenu[$d['id']] = $d['name'];
        }
        return $arrMenu;
    }

    public static function getSubMenuParent($language_id) {
        $criteria = new CDbCriteria;
        $criteria->compare('t.language_id', $language_id);
        //$criteria->compare('t.menu_id', $menu_id);
        $criteria->order = 't.order asc';
        $data = SubMenu::model()->findAll($criteria);
        $arrMenu = array();
        foreach ($data as $d) {
            $arrMenu[$d['id']] = $d['name'];
        }
        return $arrMenu;
    }

    public static function getNewsParent($language_id) {
        $criteria = new CDbCriteria;
        $criteria->compare('t.language_id', $language_id);
        $data = News::model()->findAll($criteria);
        $arrNews = array();
        foreach ($data as $d) {
            $arrNews[$d['id']] = $d['name'];
        }
        return $arrNews;
    }

    public static function getAllMenu() {
        $criteria = new CDbCriteria;
        $criteria->compare('t.active', 1);
        $criteria->order = 't.order asc';
        $data = Menu::model()->findAll($criteria);
        return $data;
    }

    public static function getCategoryByParent($id) {
        $parent = Category::model()->findByAttributes(array(
            'id' => $id
                ));
        return $parent['name'];
    }

    public static function getAllCategoryByParent($id) {
        $criteria = new CDbCriteria();
        $criteria->condition = 't.active=:pactive AND t.parent=:parent';
        $criteria->params = array(':pactive' => 1, ':parent' => $id);
        $category = Category::model()->findAll($criteria);
        return $category;
    }

    public static function getProductByCategoryParent($id) {
        $criteria = new CDbCriteria();
        $criteria->select = 't.*';
        $criteria->with = 'category';
        $criteria->join = 'JOIN categories c on c.id = t.category_id';
        $criteria->condition = 't.active=:pactive AND c.active=:cactive AND c.parent=:parent';
        $criteria->params = array(':parent' => $id, ':pactive' => 1, ':cactive' => 1);
        $product = Product::model()->findAll($criteria);
        return $product;
    }

    public static function getProductByCategory($id) {
        $criteria = new CDbCriteria();
        $criteria->with = 'category';
        $criteria->join = 'JOIN categories c on c.id = t.category_id';
        $criteria->condition = 't.active=:pactive AND c.active=:cactive AND t.category_id=:category_id OR c.parent=:parent';
        $criteria->params = array(':pactive' => 1, ':cactive' => 1, ':category_id' => $id, ':parent' => $id);
        $product = Product::model()->findAll($criteria);
        return $product;
    }
    
    public static function checkCatebySlug($slug){
        $criteria = new CDbCriteria();
        $criteria->select = 't.*';
        $criteria->compare('slug', $slug);
        $cate = Category::model()->find($criteria);
        return $cate['id'];
    }
}

?>